<?php
/**
 *  Trida vytvari pripojeni k databazi, vytvari novy objekt pro obaleni vysledku mysql
 *
 */  
class DB_Mysql{
  protected $user;
  protected $pass;
  protected $dbhost;
  protected $dbname;
  protected $dbh;      //database connection handle


  public function __construct($user,$pass,$dbhost,$dbname){
    $this->user = $user;
    $this->pass = $pass;
    $this->dbhost = $dbhost;
    $this->dbname = $dbname;
  }

  protected function connect(){
    $this->dbh = mysql_pconnect($this->dbhost,$this->user,$this->pass);
    if(!is_resource($this->dbh)){
      throw new Exception;
    }
    if(!mysql_select_db($this->dbname,$this->dbh)) {
      throw new Exception;
    }
  }
  /**
   * tuto metodu muzem volat pro vsechny prikazy sql
   * params query   
   * return result
   */        
  public function execute($query){
  if(!$this->dbh) {
    $this->connect();  
  }
  $ret  = mysql_query($query,$this->dbh);
    if(!$ret) {
      throw new Exception;
    }
    else if (!is_resource($ret)) {
      return TRUE ; 
    } else {
      $stmt = new DB_MysqlStatement($this->dbh, $query);
      $stmt->result = $ret;
      return $stmt;
    }
  }
  
   //public function sql_freeresult() {
   // mysql_freeresult($this->result);  
   // }
  
  public function prepare($query) {
    if(!$this->dbh) {
      $this->connect();
    }
    return new DB_MysqlStatement($this->dbh, $query);   
  }
	/**
	* Build sql statement from array for insert/update/select statements
	*
	* Idea for this from Ikonboard
	* Possible query values: INSERT, INSERT_SELECT, MULTI_INSERT, UPDATE, SELECT
	*
	* If a key is 'module_name' and firebird used it gets adjusted to '"module_name"'
	* on INSERT, INSERT_SELECT, UPDATE and SELECT
	*/
	public function sql_build_array($query, $assoc_ary = false)
	{
		if (!is_array($assoc_ary))
		{
			return false;
		}

		$fields = $values = array();

		if ($query == 'INSERT' || $query == 'INSERT_SELECT')
		{
			foreach ($assoc_ary as $key => $var)
			{
				$fields[] = ($key == 'module_name' && SQL_LAYER == 'firebird') ? '"' . $key . '"' : $key;

				if (is_null($var))
				{
					$values[] = 'NULL';
				}
				else if (is_string($var))
				{
					$values[] = "'" . $this->sql_escape($var) . "'";
				}
				else if (is_array($var) && is_string($var[0]))
				{
					// This is used for INSERT_SELECT(s)
					$values[] = $var[0];
				}
				else
				{
					$values[] = (is_bool($var)) ? intval($var) : $var;
				}
			}

			$query = ($query == 'INSERT') ? ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')' : ' (' . implode(', ', $fields) . ') SELECT ' . implode(', ', $values) . ' ';
		}
		else if ($query == 'MULTI_INSERT')
		{
			$ary = array();
			foreach ($assoc_ary as $id => $sql_ary)
			{
				$values = array();
				foreach ($sql_ary as $key => $var)
				{
					if (is_null($var))
					{
						$values[] = 'NULL';
					}
					else if (is_string($var))
					{
						$values[] = "'" . $this->sql_escape($var) . "'";
					}
					else
					{
						$values[] = (is_bool($var)) ? intval($var) : $var;
					}
				}
				$ary[] = '(' . implode(', ', $values) . ')';
			}

			$query = ' (' . implode(', ', array_keys($assoc_ary[0])) . ') VALUES ' . implode(', ', $ary);
		}
		else if ($query == 'UPDATE' || $query == 'SELECT')
		{
			$values = array();
			foreach ($assoc_ary as $key => $var)
			{
				$key = ($key == 'module_name' && SQL_LAYER == 'firebird') ? '"' . $key . '"' : $key;

				if (is_null($var))
				{
					$values[] = "$key = NULL";
				}
				else if (is_string($var))
				{
					$values[] = "$key = '" . $this->sql_escape($var) . "'";
				}
				else
				{
					$values[] = (is_bool($var)) ? "$key = " . intval($var) : "$key = $var";
				}
			}
			$query = implode(($query == 'UPDATE') ? ', ' : ' AND ', $values);
		}

		return $query;
	}
  
  
	/**
	* Escape string used in sql query
	*/
	protected function sql_escape($msg)
	{
		if (!$this->db_connect_id)
		{
			return @mysql_real_escape_string($msg);
		}

		return @mysql_real_escape_string($msg, $this->db_connect_id);
	}
	/**
	* Get last inserted id after insert statement
	*/
	public function sql_nextid()
	{
		return ($this->dbh) ? @mysql_insert_id($this->dbh) : false;
	}
  
  
  
}
/** 
 * Trida obalujici vysledek dotazu
 * zaroven impelemntuje metodu execute, takze dotazu muzeme predaj jen jmeno jako parametr 
 * ktery je v dotazu oznacen jako napr  :1  
 */  

class DB_MysqlStatement {
  
  public $result;
  public $query;
  protected $dbh;
  public $binds;
    
  public function __construct($dbh,$query) {
    $this->query = $query;
    $this->dbh = $dbh;
    if (!is_resource($dbh)) {
      throw new Exception("Not a valid database connection");
    }  
  }
  public function fetch_row() {
    if(!$this->result) {
      throw new Exception("Dotaz nezpracovan");
    }
    return mysql_fetch_row($this->result);
  }
  public function fetch_assoc() {
    return mysql_fetch_assoc($this->result);
  }
  public function fetchall_assoc() {
    $retval = array() ;
    while($row = $this->fetch_assoc()) {
      $retval[] = $row;
    }
    return $retval; 
  }
  
  public function execute() {
    $binds = func_get_args();
    
    foreach($binds as $index => $name) {
      $this->binds[$index+1] = $name; 
    }
    $cnt = count($binds);
    $query = $this->query;
    if(!empty($this->binds)){
      foreach ($this->binds as $ph => $pv) {
        $query = str_replace(":$ph", "'".mysql_escape_string($pv). "'",$query );
      }
    }
    $this->result = mysql_query($query, $this->dbh);
    
    if(!$this->result){
      //throw new MysqlException;
      throw new MySqlException;
    }
    return $this;
  }
  
  public function sql_freeresult() {
    mysql_freeresult($this->result);  
  }
  
}

?>
